# 和poi有关的操作
from fastapi import APIRouter,Query,Body

import json

from DB_Utils.vikaDB import VikaPOISheet,VikaCommentSheet #导入vika表的操作实例

# 创建二级路由
router = APIRouter(prefix="/vika") # 前缀为vika

@router.get('/test')
def test():
    return {"msg": "test"}

# 从vika中获取所有POI数据
@router.get("/getPOIList")
async def getPOIList():
    try:
        # 筛选出未删除的poi
        poi_records = VikaPOISheet.records.filter(is_deleta='0')
        poi_list = [poiItem.json() for poiItem in poi_records]
        
        for poi in poi_list:
            poi['long_and_latitu'] = json.loads(poi['long_and_latitu']) #将经纬度转换为json格式

        return {"msg": "获取POI列表成功", "poiList": poi_list}

    except Exception as e:
        print(e)
        return {"msg": str(e)}
    
# 从vika中获取POI相关的所有评论数据
@router.get("/getComments")
async def getComments(poi_id: str = Query()):
    try:
        comment_records = VikaCommentSheet.records.filter(link_id=poi_id) #筛选符合条件的评论
        comment_list = [commentItem.json() for commentItem in comment_records]
        return {"msg": "获取评论列表成功", "commentList": comment_list,"length":len(comment_list)}

    except Exception as e:
        print(e)
        return {"msg": str(e)}
    


# 添加POI数据到vika表中
@router.post("/addPOI")
async def addPOI(poi = Body()):
    try:
        print(poi)
        poi['long_and_latitu'] = json.dumps(poi['long_and_latitu']) #将经纬度转换为json格式
        VikaPOISheet.records.create(poi)
        return {"msg": "添加POI成功"}

    except Exception as e:
        print(e)
        return {"msg": str(e)}
    
# 添加评论数据到vika表中
@router.post("/addComment")
async def addComment(comment = Body()):
    try:
        print(comment)
        VikaCommentSheet.records.create(comment)
        return {"msg": "添加评论成功"}

    except Exception as e:
        print(e)
        return {"msg": str(e)}
    


@router.post('/deletePOI')
# TODO
async def deletePOI(poiID = Body()):
    try:
        print(poiID.get('poi_id'))
        row = VikaPOISheet.records.get(poi_id=poiID.get('poi_id'))
        row.is_deleta = '1' #逻辑删除,置位为1
        return {"msg": "删除POI成功"}

    except Exception as e:
        print(e)
        return {"msg": str(e)}